package com.wzy.service.impl;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wzy.entity.Battle;
import com.wzy.entity.Blog;
import com.wzy.mapper.BattleMapper;
import com.wzy.service.BattleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzy.util.Const;
import com.wzy.util.Pager;
import com.wzy.util.textTranfromHtmlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wzy
 * @since 2021-02-09
 */
@Service
public class BattleServiceImpl extends ServiceImpl<BattleMapper, Battle> implements BattleService {

    @Resource
    private BattleMapper battleMapper;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 查询所有的战役信息
     *
     * @return
     */
    @Cacheable(key = "'battles'", value = "battle")
    @Override
    public List<Battle> listBattle() {
        List<Battle> collect = baseMapper.selectList(null).stream().filter(item -> item.getBattleId() != 0).collect(Collectors.toList());
        return collect;
    }

    @Override
    public Pager<Battle> list(Battle condition, Integer page) {
        List<Battle> datas = this.battleMapper.selectByCondition(condition, (page - 1) * Const.PAGE_SIZE, Const.PAGE_SIZE);
        int size = this.battleMapper.size(condition);
        return new Pager<>(datas, size, page, Const.PAGE_SIZE);
    }

    @Override
    public List<Battle> listNotAppend() {
        return this.battleMapper.selectNotAppend();
    }

    /**
     * 根据id查询战役
     *
     * @param battleId
     * @return
     */
    @Override
    public Blog selectBattleDetailById(Long battleId) {
        //去redis中查
        Blog battle = (Blog) redisTemplate.opsForValue().get("battle" + battleId);
        //没查到去数据库中查
        if (battle == null) {
            battle = battleMapper.selectBattleDetailById(battleId);
            battle.setContent(textTranfromHtmlUtils.markdownToHtmlExtensions(battle.getContent()));
            redisTemplate.opsForValue().set("battle" + battleId, battle);
            redisTemplate.expire("battle" + battleId, 5, TimeUnit.MINUTES);
        }
        return battle;
    }
}
